<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户管理</span>
      </div>
      <div class="filter-container">
        <el-input
          v-model="listQuery.username"
          placeholder="用户名"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" @click="handleReset">
          重置
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="头像" align="center" width="80">
          <template #default="scope">
            <el-image
              style="width: 40px; height: 40px; border-radius: 50%"
              :src="scope.row.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="用户名" prop="username" align="center" min-width="120" />
        <el-table-column label="昵称" prop="profile.nickname" align="center" min-width="120" />
        <el-table-column label="邮箱" prop="email" align="center" min-width="150" />
        <el-table-column label="电话" prop="profile.phone" align="center" min-width="120" />
        <el-table-column label="角色" prop="role" align="center" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'success'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="默认地址" align="center" min-width="200">
          <template #default="scope">
            {{ scope.row.defaultAddress || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" min-width="150">
          <template #default="scope">
            {{ formatDate(scope.row.createAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button 
              type="warning" 
              size="small" 
              @click="handleResetPassword(scope.row)"
              :disabled="scope.row.role === 'admin'"
            >
              重置密码
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.role === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.pageNum"
        :limit.sync="listQuery.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination'
import cloudbase from '@cloudbase/js-sdk'

export default {
  name: 'UserView',
  components: { Pagination },
  setup() {
    const listLoading = ref(false)
    const list = ref([])
    const total = ref(0)

    const listQuery = reactive({
      pageNum: 1,
      pageSize: 10,
      username: ''
    })

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '-'
      const d = new Date(date)
      return d.toLocaleString()
    }

    // 获取用户列表
    const getList = async () => {
      listLoading.value = true
      try {
        const app = cloudbase.init({
          env: "cloud1-2gozbkkk09f11d05"
        })
        
        await app.auth().signInAnonymously()
        
        const res = await app.callFunction({
          name: 'User',
          data: { 
            action: 'query',
            pageNum: listQuery.pageNum,
            pageSize: listQuery.pageSize,
            username: listQuery.username || undefined
          }
        })

        if (res.result && res.result.code === 200) {
          let users = Array.isArray(res.result.data) ? res.result.data : [res.result.data]
          // 批量获取头像临时链接
          await Promise.all(users.map(async user => {
            if (user.profile && user.profile.avatar && user.profile.avatar.startsWith('cloud://')) {
              try {
                const avatarRes = await app.callFunction({
                  name: 'Book', // 这里用Book云函数的getImageUrl
                  data: {
                    action: 'getImageUrl',
                    fileID: user.profile.avatar
                  }
                })
                if (avatarRes.result && avatarRes.result.code === 200) {
                  user.avatarUrl = avatarRes.result.data.tempFileURL
                } else {
                  user.avatarUrl = ''
                }
              } catch (e) {
                user.avatarUrl = ''
              }
            } else {
              user.avatarUrl = user.profile && user.profile.avatar ? user.profile.avatar : ''
            }
          }))
          list.value = users
          total.value = res.result.total || users.length
        } else {
          ElMessage.error(res.result.message || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
      } finally {
        listLoading.value = false
      }
    }

    // 处理搜索
    const handleFilter = () => {
      listQuery.pageNum = 1
      getList()
    }

    // 处理重置
    const handleReset = () => {
      listQuery.username = ''
      listQuery.pageNum = 1
      getList()
    }

    // 处理重置密码
    const handleResetPassword = async (row) => {
      try {
        await ElMessageBox.confirm('确定要重置该用户的密码为"123456"吗？', '提示', {
          type: 'warning'
        })
        
        const app = cloudbase.init({
          env: "cloud1-2gozbkkk09f11d05"
        })
        
        await app.auth().signInAnonymously()
        
        const res = await app.callFunction({
          name: 'User',
          data: { 
            action: 'resetPassword',
            userId: row._id,
            adminId: 'cc3a417967bdddc506b7ec641bc9abd4' // 这里需要替换为当前登录的管理员ID
          }
        })

        if (res.result && res.result.code === 200) {
          ElMessage.success('密码重置成功')
        } else {
          ElMessage.error(res.result.message || '密码重置失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('重置密码失败:', error)
          ElMessage.error('重置密码失败')
        }
      }
    }

    // 处理删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
          type: 'warning'
        })
        
        const app = cloudbase.init({
          env: "cloud1-2gozbkkk09f11d05"
        })
        
        await app.auth().signInAnonymously()
        
        const res = await app.callFunction({
          name: 'User',
          data: { 
            action: 'delete',
            userId: row._id,
            adminId: 'cc3a417967bdddc506b7ec641bc9abd4' // 这里需要替换为当前登录的管理员ID
          }
        })

        if (res.result && res.result.code === 200) {
          ElMessage.success('删除成功')
          getList()
        } else {
          ElMessage.error(res.result.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error)
          ElMessage.error('删除用户失败')
        }
      }
    }

    onMounted(() => {
      getList()
    })

    return {
      listLoading,
      list,
      total,
      listQuery,
      handleFilter,
      handleReset,
      handleResetPassword,
      handleDelete,
      formatDate,
      getList
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
</style> 